package com.xique.door.project.miniprogram.biz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.door.api.dto.BaseUserDTO;
import com.xique.door.api.model.LoginAppUser;
import com.xique.door.bean.domain.BaseUserV1;
import com.xique.door.project.miniprogram.bean.domian.WeixinCode2Session;
import com.xique.door.project.miniprogram.biz.service.IMiniLoginBizService;
import com.xique.door.service.IBaseUserService;
import com.xique.door.util.WechatUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shd
 * @create 2022/4/13 20:07
 */
@Service
@Slf4j
public class MiniLoginBizServiceImpl implements IMiniLoginBizService {

    @Value("${wx.mini.appId}")
    private String appId;

    @Value("${wx.mini.secret}")
    private String secret;

    @Autowired
    private WechatUtils wechatUtils;

    @Autowired
    private IBaseUserService userService;

    @Override
    public R<String> getPhone(String code) {
        R<String> result = wechatUtils.getPhone(appId, secret, code);
        if (R.FAIL == result.getCode()) {
            return R.fail(result.getMsg());
        }
        String phone = result.getData();
        return R.ok(phone);
    }

    @Override
    public R<LoginAppUser>  wxLogin(String phone, String code) {
        // TODO 判断是否是已存在用户,存在 直接去数据库数据并登录， 不存在去取微信数据并注册
        R<WeixinCode2Session> result = wechatUtils.getCode2Session(appId, secret, code);
        if (R.FAIL == result.getCode()) {
            return R.fail(result.getMsg());
        }
        WeixinCode2Session session = result.getData();

        //1、手机号和openId组合查询到用户，则直接返回
        List<BaseUserV1> openIdAndPhoneUsers = userService.selectBaseUserByParkMiniOpenIdAndPhone(session.getOpenId(), phone);
        if (!openIdAndPhoneUsers.isEmpty()) {
            BaseUserV1 openIdAndPhoneUser = openIdAndPhoneUsers.get(0);
            if (StrUtil.isEmpty(openIdAndPhoneUser.getWechatUnionid())) {
                openIdAndPhoneUser.setWechatUnionid(session.getUnionId());
                userService.updateById(openIdAndPhoneUser);
            }
            return R.ok(transformLoginAppUser(openIdAndPhoneUser));
        }

        List<BaseUserV1> openIdUsers = userService.selectBaseUserV1ByOpenId(session.getOpenId());
        List<BaseUserV1> phoneUserList = userService.selectBaseUserV1sByLoginName(phone);

        //2、openId查不到，手机号匹配到(手机号一样，openId不一样)
        if (openIdUsers.isEmpty() && !phoneUserList.isEmpty()) {
            BaseUserV1 phoneUser = phoneUserList.get(0);
            if (StrUtil.isNotEmpty(phoneUser.getWechatOpenid())) {
                log.error("[门禁小程序]手机号已经被其他微信绑定,OPENID：{},微信返回手机号：{}，数据库用户对应手机号：{}", session.getOpenId(), phone, openIdUsers.get(0).getCellphone());
                return R.fail("该手机号已经被其他微信绑定，请联系管理员！");
            }
            //给baseUser填充移动端信息
            if (StrUtil.isEmpty(phoneUser.getWechatUnionid())) {
                phoneUser.setWechatUnionid(session.getUnionId());
                phoneUser.setSessionKey(session.getSessionKey());
                userService.updateById(phoneUser);
            }
            return R.ok(transformLoginAppUser(phoneUser));
        }

        //3、openId查的到，手机号查不到(openId一样，手机号不一样)
        if (!openIdUsers.isEmpty() && phoneUserList.isEmpty()) {
            BaseUserV1 openIdUser = openIdUsers.get(0);
            if (StrUtil.isEmpty(openIdUser.getCellphone())) {
                //用户手机号为空，修改用户
                openIdUser.setCellphone(phone);
                openIdUser.setSessionKey(session.getSessionKey());
                openIdUser.setWechatUnionid(session.getOpenId());
                userService.updateById(openIdUser);
                return R.ok(transformLoginAppUser(openIdUser));
            }
            //一个微信可以绑定多个手机号登录
            log.error("[门禁小程序]微信已经绑定了别的手机号,先创建新用户，openId：{},微信返回手机号：{}，数据库用户对应手机号：{}", session.getOpenId(), phone, openIdUser.getCellphone());
        }

        //4、手机号查不到，OPENID查不到，直接创建新用户
        BaseUserV1 insert = new BaseUserV1();
        insert.setUserName(phone);
        insert.setCellphone(phone);
        insert.setSessionKey(session.getSessionKey());
        insert.setWechatUnionid(session.getUnionId());
        insert.setWechatOpenid(session.getOpenId());
        userService.save(insert);

        return R.ok(transformLoginAppUser(insert));

//        BaseUserV1 user = userService.selectBaseUserV1ByOpenId(session.getOpenId());
//        List<BaseUserV1> phoneUserList = userService.selectBaseUserV1sByLoginName(phone);
//
//        if (StringUtils.isNotNull(user)) {
//            if (StringUtils.isNotEmpty(user.getCellphone()) && !StringUtils.equals(user.getCellphone(), phone)) {
//                return R.fail("绑定手机号不正确");
//            }
//
//            if (StringUtils.isEmpty(user.getCellphone())) {
//                BaseUserV1 update = new BaseUserV1();
//                update.setId(user.getId());
//                update.setCellphone(phone);
//
//                userService.updateById(update);
//
//                user.setCellphone(phone);
//            }
//
//            return R.ok(transformLoginAppUser(user));
//        }
//
//        if (CollectionUtil.isNotEmpty(phoneUserList)) {
//            if (phoneUserList.size() > 1) {
//                return R.fail("当前手机号存在多个登录信息，请联系管理员处理");
//            }
//            BaseUserV1 phoneUser = phoneUserList.get(0);
//            BaseUserV1 update = new BaseUserV1();
//            update.setId(phoneUser.getId());
//            update.setWechatOpenid(session.getOpenId());
//            update.setWechatUnionid(session.getUnionId());
//            update.setSessionKey(session.getSessionKey());
//
//            userService.updateById(update);
//
//            phoneUser.setWechatOpenid(session.getOpenId());
//            phoneUser.setWechatUnionid(session.getUnionId());
//            phoneUser.setSessionKey(session.getSessionKey());
//
//            return R.ok(transformLoginAppUser(phoneUser));
//        }
    }

    private LoginAppUser transformLoginAppUser(BaseUserV1 user) {
        LoginAppUser loginAppUser = new LoginAppUser();
        loginAppUser.setBaseUserId(user.getId());
        loginAppUser.setUserName(user.getUserName());
        loginAppUser.setOpenId(user.getWechatOpenid());
        loginAppUser.setUnionId(user.getWechatUnionid());
        loginAppUser.setSessionKey(user.getSessionKey());
        loginAppUser.setUser(OrikaUtil.convert(user, BaseUserDTO.class));
        return loginAppUser;
    }

    @Override
    public R<LoginAppUser>  phoneLogin(String phone) {

        List<BaseUserV1> phoneUserList = userService.selectBaseUserV1sByLoginName(phone);
        if (phoneUserList.size() > 1) {
            return R.fail("当前手机号存在多个登录信息，请联系管理员处理");
        }

        if (phoneUserList.size() == 1){
            BaseUserV1 phoneUser = phoneUserList.get(0);
            return R.ok(transformLoginAppUser(phoneUser));
        }
        //手机号不存在，创建用户
        BaseUserV1 insert = new BaseUserV1();
        insert.setUserName(phone);
        insert.setCellphone(phone);
        userService.save(insert);
        return R.ok(transformLoginAppUser(insert));

        
//        BaseUserV1 user = userService.selectBaseUserV1ByLoginName(phone);
//        if (StringUtils.isNotNull(user)) {
//            if (StringUtils.isEmpty(user.getCellphone())) {
//                BaseUserV1 update = new BaseUserV1();
//                update.setId(user.getId());
//                update.setCellphone(phone);
//
//                userService.updateById(update);
//
//                user.setCellphone(phone);
//            }
//            return R.ok(transformLoginAppUser(user));
//        }
//        List<BaseUserV1> phoneUserList = userService.selectBaseUserV1sByLoginName(phone);
//        if (CollectionUtil.isNotEmpty(phoneUserList)) {
//            if (phoneUserList.size() > 1) {
//                return R.fail("当前手机号存在多个登录信息，请联系管理员处理");
//            }
//            BaseUserV1 phoneUser = phoneUserList.get(0);
//            BaseUserV1 update = new BaseUserV1();
//            update.setId(phoneUser.getId());
//            update.setWechatOpenid(user.getWechatOpenid());
//            update.setWechatUnionid(user.getWechatUnionid());
//            update.setSessionKey(user.getSessionKey());
//
//            userService.updateById(update);
//
//            phoneUser.setWechatOpenid(user.getWechatOpenid());
//            phoneUser.setWechatUnionid(user.getWechatUnionid());
//            phoneUser.setSessionKey(user.getSessionKey());
//
//            return R.ok(transformLoginAppUser(phoneUser));
//        }
//
//        BaseUserV1 insert = new BaseUserV1();
//        insert.setUserName(phone);
//        insert.setCellphone(phone);
//        insert.setWechatOpenid(user.getWechatOpenid());
//        insert.setSessionKey(user.getSessionKey());
//        insert.setWechatUnionid(user.getWechatUnionid());
//
//        boolean isSuccess = userService.save(insert);
//        if (!isSuccess) {
//            return R.fail("注册失败");
//        }
//
//        return R.ok(transformLoginAppUser(insert));
    }
}
